package com.ld.admin.service.oa.work;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;

import org.springframework.stereotype.Service;

import com.ld.admin.model.oa.work.MonthlyReportModel;
import com.ld.shieldsb.common.core.model.Result;
import com.ld.shieldsb.common.core.util.StringUtils;
import com.ld.shieldsb.common.web.BasicService;
import com.ld.shieldsb.common.web.StaticParams;
import com.ld.shieldsb.common.web.util.Web;
import com.ld.shieldsb.dao.model.PageNavigationBean;
import com.ld.shieldsb.dao.model.QueryModel;

/**
 * @ClassName MonthlyReportService
 * @Description 工作月报服务类
 * @Author 付信豪
 * @Date 2019/8/20 10:01
 * @ModifyDate 2019/8/20 10:01
 * @Version 1.0
 */
@Service
public class MonthlyReportService extends BasicService {
    // 用于子类覆盖，扩展doSearch方法中QueryModel的处理（标准queryModel处理完，查询进行前的处理）
    @Override
    protected QueryModel extendDealQuery(QueryModel queryModel) {
        // TODO Auto-generated method stub
        return super.extendDealQuery(queryModel);
    }

    // 用于子类覆盖，扩展doSearch方法中PageNavigationBean的处理（查询完成后进行）
    @Override
    protected <T> PageNavigationBean<T> extendDealPageNavigationBean(PageNavigationBean<T> pageNavigationBean) {
        // TODO Auto-generated method stub
        return super.extendDealPageNavigationBean(pageNavigationBean);
    }

    // 删除方法子类扩展（删除完成后进行）
    @Override
    protected <T> boolean extendRemove(Boolean flag, Class<T> classOfT, String key, Object value, Integer status, Long userId) {
        // TODO Auto-generated method stub
        return flag;
    }

    // AddOrUpdate扩展（AddOrUpdate方法完成后进行）
    @Override
    protected <T> boolean extendAddOrUpdate(Boolean flag, T modelBean, boolean update, String key, Long userId) {
        // TODO Auto-generated method stub
        return flag;
    }

    /**
     * @Description 设置本月和下月的开始第一天和最后一天
     * @Author 付信豪
     * @Date 2019/8/21 14:32
     * @ModifyDate 2019/8/21 14:32
     * @Params [date]
     * @Return java.lang.String
     */
    public void getTimeInterval() {
        // 当前的日期
        LocalDate today = LocalDate.now();
        // 本月的第一天
        LocalDate thisMonthFirstday = LocalDate.of(today.getYear(), today.getMonth(), 1);
        // 本月的最后一天
        LocalDate thisMonthLastDay = today.with(TemporalAdjusters.lastDayOfMonth());
        request.setAttribute("start", thisMonthFirstday);// 本月的第一天
        request.setAttribute("end", thisMonthLastDay);// //本月的最后一天
        today = today.plusMonths(1);
        LocalDate nextMonthFirstday = LocalDate.of(today.getYear(), today.getMonth(), 1);
        LocalDate nextMonthLastDay = today.with(TemporalAdjusters.lastDayOfMonth());
        request.setAttribute("nextMonthStart", nextMonthFirstday);// 下个月的第一天
        request.setAttribute("nextMonthEnd", nextMonthLastDay);// //下个月的最后一天

    }

    /**
     * @Description 根据条件是否初始化搜索开始日期
     * @Author 付信豪
     * @Date 2019/9/4 9:42
     * @ModifyDate 2019/9/4 9:42
     * @Params [sign]
     * @Return void
     */
    public void initializeSearchDate(String sign) {
        if (StringUtils.isEmpty(sign) || "lowLevel".equals(sign)) {
            String yearMonth = "";
            // 当前的日期
            LocalDate today = LocalDate.now();
            // 当前的年份
            int year = today.getYear();
            // 当前的月份
            int monthValue = today.getMonth().getValue();
            if (monthValue >= 10) {
                yearMonth = year + "-" + monthValue;
            } else {
                yearMonth = year + "-0" + monthValue;
            }
            request.setAttribute("yearMonth", yearMonth);// 下个月的第一天
        } else {
            return;
        }
    }

    /**
     * @Description 更新和添加
     * @Author 付信豪
     * @Date 2019/8/21 14:23
     * @ModifyDate 2019/8/21 14:23
     * @Params [model]
     * @Return java.lang.Object
     */
    public Object addOrUpdate(MonthlyReportModel model) {
        int length = model.getContent().length();
        int length1 = model.getNextMonthContent().length();
        if (length > 20000) {
            return Web.Response.error("本月内容不能超过20000字符");
        } else if (length1 > 20000) {
            return Web.Response.error("下月计划内容不能超过20000字符");

        } else {
            if (StringUtils.isEmpty(model.getId())) {// id为空时
                String start = dateTurnLocalDate(model.getStartDate()).toString();
                String end = dateTurnLocalDate(model.getEndDate()).toString();
                if (start.compareTo(end) > 0) {
                    return Web.Response.error("本月报报的开始时间不能大于结束时间");
                }
                if (model.getNextMonthStartDate() != null && model.getNextMonthStartDate() != null) {
                    String nextStart = dateTurnLocalDate(model.getNextMonthStartDate()).toString();
                    String nextEnd = dateTurnLocalDate(model.getNextMonthEndDate()).toString();
                    if (nextStart.compareTo(nextEnd) > 0) {
                        return Web.Response.error("下月计划的开始时间不能大于结束时间");
                    }
                }

                LocalDate startDate = LocalDate.parse(start, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
                // 当前日期月份的第一天
                LocalDate thisMonthFirstday = LocalDate.of(startDate.getYear(), startDate.getMonth(), 1);
                // 当前日期月份的随后一天
                LocalDate thisMonthLastDay = startDate.with(TemporalAdjusters.lastDayOfMonth());
                QueryModel queryModel = new QueryModel();
                queryModel.addLike("startDate", thisMonthFirstday.toString());
                queryModel.addLike("endDate", thisMonthLastDay.toString());
                queryModel.addEq("createBy", Web.Util.getSessionUserId(request));
                queryModel.addEq("state", StaticParams.STATE_NORMAL);
                MonthlyReportModel monthlyReport = getBaseDAO().getOne(MonthlyReportModel.class, queryModel);
                if (monthlyReport != null) {// 查询出的结果不为空
                    return Web.Response.error("本月月报已存在！请删除之后再添加或者直接修改本月月报");
                }
            }
            Result result = super.addOrUpdate(model, model.getId() != null);
            return Web.Response.result(result);
        }
    }

    /**
     * @Description Date转LocalDate
     * @Author 付信豪
     * @Date 2019/8/23 16:22
     * @ModifyDate 2019/8/23 16:22
     * @Params [date]
     * @Return java.time.LocalDate
     */
    public static LocalDate dateTurnLocalDate(Date date) {
        if (null == date) {
            return null;
        }
        return date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
    }
}